import React,{Component} from 'react';
import {Link} from 'react-router-dom';
import $ from 'jquery';
import history from '../history';
import { Form, Input, Tooltip, Icon, Row, Col, Checkbox, Button, AutoComplete,message} from 'antd';
import Captcha from '../captcha/Captcha';
require("./Register.css");
// const FormItem = Form.Item;

// const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;

class Resgister extends Component{

    constructor(props){
        super(props);
        this.state={
            confirmDirty: false,
            autoCompleteResult: []
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            console.log('表格的接收值: ', values);

            if(values.agreement === true){
                $.ajax({
                    url: 'http://localhost:8008/user/save',
                    dataType: "json",
                    contentType:"application/json",
                    data: JSON.stringify(values),
                    method: 'POST',
                    success: function(data) {
                      console.log("data",data);
                      if(data !== null){
                          message.success("注册成功!"+values.userName+"，欢迎您！");
                        history.push("/");
                      }
                    },
                    error: function(xhr) {
                    }
                })
            }else{
                // alert("请您先阅读条款!");
                message.info("请您先阅读条款!");
            }
            
          }
        });

        

      }
    
      handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
      }
    
      compareToFirstPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('passwd')) {
          callback('两次输入的密码不匹配!');
        } else {
          callback();
        }
      }
    
      validateToNextPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
          form.validateFields(['confirm'], { force: true });
        }
        callback();
      }
    
      handleWebsiteChange = (value) => {
        let autoCompleteResult;
        if (!value) {
          autoCompleteResult = [];
        } else {
          autoCompleteResult = ['@qq.com', '@163.com', '@icerno.com','@foxmail.com'].map(domain => `${value}${domain}`);
        }
        this.setState({ autoCompleteResult });
      }

        inputOnBlur = ()=>{
            this.setState({ 
                
            })
            var demo = this.props.form;
            demo.validateFields((err,values) => {
                $.ajax({
                    url: 'http://localhost:8008/user/check',
                    dataType: "json",
                    contentType:"application/json",
                    data: JSON.stringify(values.userName),
                    method: 'POST',
                    success: function(data) {
                      console.log("data",data);
                      if(data === true){
                        message.error("用户名被占用!");
                        history.go(0);
                      }
                    },
                    error: function(xhr) {
                        
                    }
                })
            });
        }

        inputOnFocus = ()=> { this.setState({ isShowCheckBox:true }) } 

    render() {

        const { getFieldDecorator } = this.props.form;
        const { autoCompleteResult } = this.state;

        const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 8 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
        },
        };

        const tailFormItemLayout = {
        wrapperCol: {
            xs: {
            span: 24,
            offset: 0,
            },
            sm: {
            span: 16,
            offset: 8,
            },
        },
        };

        const websiteOptions = autoCompleteResult.map(website => (
        <AutoCompleteOption key={website}>{website}</AutoCompleteOption>
        ));


        return (
            <div className="bigdiv">
                <Form onSubmit={this.handleSubmit} className="form" autoComplete="off">

                    <Form.Item
                    {...formItemLayout}
                    label={(
                        <span>
                        昵称&nbsp;
                        <Tooltip title="您想要我们怎么称呼您?">
                            <Icon type="question-circle-o" />
                        </Tooltip>
                        </span>
                    )}
                    >
                    {getFieldDecorator('userName', {
                        rules: [{ required: true, message: '请输入您的昵称!', whitespace: true }],
                    })(
                        <Input 
                            placeholder="请输入昵称!"
                            onPressEnter={this.startSearch}
                            onBlur={this.inputOnBlur}
                            onFocus={this.inputOnFocus}
                        />
                    )}
                    </Form.Item>
                   
                    <Form.Item
                    {...formItemLayout}
                    label="密码"
                    >
                    {getFieldDecorator('passwd', {
                        rules: [{
                        required: true, message: '请输入您的密码!',
                        }, {
                        validator: this.validateToNextPassword,
                        }],
                    })(
                        <Input type="passwd" />
                    )}
                    </Form.Item>
                    <Form.Item
                    {...formItemLayout}
                    label="确认密码"
                    >
                    {getFieldDecorator('confirm', {
                        rules: [{
                        required: true, message: '请确认您的密码!',
                        }, {
                        validator: this.compareToFirstPassword,
                        }],
                    })(
                        <Input type="passwd" onBlur={this.handleConfirmBlur} />
                    )}
                    </Form.Item>

                    <Form.Item
                    {...formItemLayout}
                    label="邮箱"
                    >
                    {getFieldDecorator('email', {
                        rules: [{
                        type: 'email', message: '您输入的邮箱格式有误!',
                        }, {
                        required: true, message: '请输入您的邮箱!',
                        }],
                    })(
                        <AutoComplete
                        dataSource={websiteOptions}
                        onChange={this.handleWebsiteChange}
                        placeholder="">
                            <Input />
                        </AutoComplete>
                        
                    )}
                    </Form.Item>
                   
                    <Form.Item
                    {...formItemLayout}
                    label="手机号"
                    >
                    {getFieldDecorator('phonenumber', {
                        rules: [
                            { required: true, message: '手机号长度有误!',len:11},
                            { message:'手机号必须是数字!',pattern:/^[0-9]+$/}
                        ]
                    })(
                        <Input 
                        // addonBefore={prefixSelector} 
                        style={{ width: '100%' }} />
                    )}
                    </Form.Item>
                    <Form.Item
                    {...formItemLayout}
                    label="验证码"
                    >
                    <Row gutter={8}>
                        <Col span={12}>
                        {getFieldDecorator('captcha', {
                            rules: [{ required: true, message: '请输入验证码!' }],
                        })(
                            <Input autoComplete="off" />
                        )}
                        </Col>
                        <Col span={12}>
                        <Captcha/>
                        </Col>
                    </Row>
                    </Form.Item>
                    <Form.Item {...tailFormItemLayout}>
                    {getFieldDecorator('agreement', {
                        valuePropName: 'checked',
                    })(
                        <Checkbox>我已经 <a href="">阅读</a> 并同意</Checkbox>
                    )}
                    </Form.Item>
                    <Form.Item {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">注册</Button>

                    <span className="cancel">
                        <Link to="/">
                            <Button type="primary" htmlType="submit">取消</Button>
                        </Link>
                    </span>
                    
                    </Form.Item>
                </Form>
            </div>
        )
    };
}

const WrappedRegistrationForm = Form.create({ name: 'register' })(Resgister);

export default WrappedRegistrationForm;